<template>
  <div id="container" class="box">
    
    <div id="toolbar" class="special_focus_toolTip">
      <fieldset style="border:1px solid aqua;border-radius:5px;">
        <legend><span style="color:yellow;font-weight:bold;font-size:18px;">地图操作</span></legend>
        <span style="color:aqua;margin-left:10px;">鼠标左键地图平移，拖动鼠标右键地图放大缩小，长按鼠标滚轮旋转地图,滚动鼠标滚轮也可放大缩小地图。</span>
      </fieldset>
      <fieldset style="border:1px solid aqua;border-radius:5px;margin-top:10px;">
        <legend><span style="color:yellow;font-weight:bold;font-size:18px;">通用设置</span></legend>
          <el-form ref="cForm" :model="cForm" :rules="cRules" label-width="80px">
            <el-form-item prop="angle">
              <span slot="label">
                <span style="color:aqua;">旋转角度</span>
              </span>
              <el-select style="width:100%;" v-model="cForm.angle">
                <el-option v-for="item in angleOptions" :key="item.value" :label="item.label" :value="parseInt(item.value)"/>
              </el-select>
            </el-form-item>
            <el-form-item prop="squre">
              <span slot="label">
                <span style="color:aqua;">缓冲单位</span>
              </span>
              <el-select style="width:100%;" v-model="cForm.square">
                <el-option v-for="item in squareOptions" :key="item.value" :label="item.label" :value="parseInt(item.value)"/>
              </el-select>
            </el-form-item>
            <el-form-item prop="dis">
              <span slot="label">
                <span style="color:aqua;">单位长宽</span>
              </span>
              <el-input-number v-model="cForm.dis" :min="0" :controls="false" style="width:92%" /><span style="color:aqua;margin-left:10px;">米</span>
            </el-form-item>
          </el-form>
        <center>
          <button style="margin-top:-8px;margin-left:10px;cursor:pointer;border:1px solid aqua;height:40px;border-radius:5px;color:aqua;background: rgba(66, 85, 99, 0.5);">
            <span style="margin-left:10px;margin-right:10px;font-size:14px;" @click="appConfig">应用设置</span>
          </button>
        </center>
      </fieldset>
      <fieldset style="border:1px solid aqua;border-radius:5px;margin-top:10px;">
        <legend><span style="color:yellow;font-weight:bold;font-size:18px;">数据分析</span></legend>
        <button style="margin-top:1px;margin-left:5px;cursor:pointer;border:1px solid aqua;height:40px;border-radius:5px;color:aqua;background: rgba(66, 85, 99, 0.5);">
          <span style="margin-left:10px;margin-right:10px;font-size:14px;" @click="loadPoints">加载数据</span>
        </button>
        <button style="margin-top:1px;margin-left:10px;cursor:pointer;border:1px solid aqua;height:40px;border-radius:5px;color:aqua;background: rgba(66, 85, 99, 0.5);">
          <span style="margin-left:10px;margin-right:10px;font-size:14px;" @click="clearResult">清除高亮</span>
        </button>
      </fieldset>
    </div>
    <div id="cesiumContainer" ></div>
  </div>
</template>
<script>
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import axios from "axios";
  export default {
    components: {},
    data() {
      return {
        angle: 30,
        square: 7,
        dis: 1000,
        datekey: null,
        points: [],
        rects:[],
        cForm: {},
        cRules: {},
        angleOptions: [{
            value: "15",
            label: "15°",
          },
          {
            value: "30",
            label: "30°",
          },
          {
            value: "45",
            label: "45°",
          },
          {
            value: "90",
            label: "90°",
          },
        ],
        squareOptions: [{
            value: "7",
            label: "7个",
          },
          {
            value: "9",
            label: "9个",
          },
          {
            value: "11",
            label: "11个",
          },
          {
            value: "13",
            label: "13个",
          },
        ],
      }
    },
    created() {
      this.getPoints();
      this.getRects();
      // this.cForm.angle = this.angle;
      // this.cForm.square = this.square;
      // this.cForm.dis = this.dis;
    },
    mounted() {
      this.init();
    },
    computed: {},
    methods: {
      getRects(){
        this.rects = [];
        let angles = this.angle;
        let dis = this.dis;
        let square = this.square;
        let circleTotal = 360;
        let count = circleTotal / angles;
        let firstRect = {
          angle: 0, 
        }
        let firstRectArray = new Array();
        for(let i=0;i<square;i++){
          let rectInfo = {};
          if(i==0){
            rectInfo.lt = { x: -dis/2, y: -dis/2 };
            rectInfo.rt = { x: dis/2,y: -dis/2 }
            rectInfo.lb = { x: -dis/2, y: dis/2 };
            rectInfo.rb = { x: dis/2, y: dis/2 };
          }else{
            rectInfo.lt = { x: -dis/2, y: -dis/2-i*dis };
            rectInfo.rt = { x: dis/2,y: -dis/2-i*dis }
            rectInfo.lb = { x: -dis/2, y: dis/2+i*dis };
            rectInfo.rb = { x: dis/2, y: dis/2+i*dis };
          }
          firstRectArray.push(rectInfo);
        }
        firstRect.rects = firstRectArray;
        this.rects.push(firstRect);
        for(let n=1;n<count;n++){
          let angle = angles * n;
          let res = {
            angle:angle
          };
          let	r = ((2*Math.PI) / 360) * angle;
          let w = dis; 
          let h	= dis;
          let rects = new Array();
          for(let m=0;m<firstRectArray.length;m++){
            let rectInfo = {};
            let centerX = 0;
            let centerY = 0;
            let x = firstRectArray[m].lt.x;
            let y = firstRectArray[m].lt.y;
            let newAX = centerX + (x - centerX) * Math.cos(r) - (y - centerY) * Math.sin(r);
            let newAY = centerY + (x - centerY) * Math.sin(r) + (y - centerY) * Math.cos(r);
            let newBX =	centerX + (x + w - centerX) * Math.cos(r) - (y - centerY) * Math.sin(r);
            let newBY = centerY + (x + w - centerX) * Math.sin(r) + (y - centerY) * Math.cos(r);
            let newCX = centerX + (x + w - centerX) * Math.cos(r) - (y + h - centerY) * Math.sin(r);
            let newCY = centerY + (x + w + centerX) * Math.sin(r) + (y + h - centerY) * Math.cos(r);
            let newDX = centerX + (x - centerX) * Math.cos(r) - (y + h - centerY) * Math.sin(r);
            let newDY = centerY + (x - centerX) * Math.sin(r) + (y + h - centerY) * Math.cos(r);
            rectInfo.lt = {x:newAX,y:newAY};
            rectInfo.rt = {x:newBX,y:newBY};
            rectInfo.rb = {x:newCX,y:newCY};
            rectInfo.lb = {x:newDX,y:newDY};
            rects.push(rectInfo)
          }
          res.rects = rects;
          this.rects.push(res);
        }
      },
      appConfig(){
        this.angle = this.cForm.angle;
        this.square = this.cForm.square;
        this.dis = this.cForm.dis;
        this.cForm.angle = this.angle;
        this.cForm.square = this.square;
        this.cForm.dis = this.dis;
        this.getRects();
        this.loadPoints();
      },
      loadPoints(){
        window.viewer.entities.removeAll();
        this.points.forEach(entity => {
          window.viewer.entities.add({
            // fromDegrees（经度，纬度，高度，椭球，结果）从以度为单位的经度和纬度值返回Cartesian3位置
            id: entity.ID,
            infos: entity,
            position: Cesium.Cartesian3.fromDegrees(entity.SPACEY,entity.SPACEX, 3000),
            point: {
              // 点的大小（像素）
              pixelSize: 8,
              // 点位颜色，fromCssColorString 可以直接使用CSS颜色
              color: Cesium.Color.GOLD,
              // 边框颜色
              outlineColor: Cesium.Color.GOLD,
              // 边框宽度(像素)
              outlineWidth: 2,
              // 显示在距相机的距离处的属性，多少区间内是可以显示的
              // distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 1500),
              heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            }
          });
        });
        window.viewer.camera.flyTo({
          destination : Cesium.Cartesian3.fromDegrees(-64.89329933564302,44.15161355126874, 220000)
        });
      },
      getPoints(){
        let url = "http://localhost:9500/points"
        axios
        .post(url)
        .then((data) => {
          this.points = data.data;
        })
        .catch((response) => {
          this.$message.error("加载失败");
        });
      },
      clearResult(){
        this.loadPoints();
      },
      init() {
        Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJkYzI1YjE0MS05YjYzLTQ4MjYtODAyMS03YTdmZTllYjlmNTIiLCJpZCI6NjE3NDQsImlhdCI6MTY5NzQ1NzM0Mn0.4iT43DCcj3UiNeg6fbf5sfEp-wcHFwYzym6YV9KV8O4';
        Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(90, -20, 110, 90);
        var VectorTileImageryProvider = Cesium.VectorTileImageryProvider;
        var viewer = new Cesium.Viewer('cesiumContainer', {
          terrainProvider: Cesium.createWorldTerrain(),
          animation: false, //是否显示动画控件
          shouldAnimate: false,
          homeButton: true, //是否显示Home按钮
          fullscreenButton: false, //是否显示全屏按钮
          baseLayerPicker: false, //是否显示图层选择控件
          geocoder: false, //是否显示地名查找控件
          timeline: false, //是否显示时间线控件
          // creditContainer: "credit", //版权图标
          sceneModePicker: false, //是否显示投影方式控件
          navigationHelpButton: false, //是否显示帮助信息控件
          infoBox: false, //是否显示点击要素之后显示的信息
          selectionIndicator: false, //是否启用地图选择
          // sceneModePicker: true,//是否启用场景选择小部件
          // requestRenderMode: false, //启用请求渲染模式
          //sceneMode: 3,
          shadows: false,
          imageryProvider: new Cesium.ArcGisMapServerImageryProvider({
            url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer',
          }),
          contextOptions: {
            webgl: {
              antialias: true,
              multisample: true
            }
          }
        });
        viewer._cesiumWidget._creditContainer.style.display = "none";
        viewer.scene.debugShowFramesPerSecond = false;
        viewer.scene.globe.enableLighting = false;  //昼夜划分
        const _this = this;

        // 扩展主图初始中心点
        viewer.homeButton.viewModel.command.beforeExecute.addEventListener(function(e) {
          console.log("dasdsadsadsa")
          // 石林中心坐标
          viewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(-65.12928073554606,43.70237969943142, 3000),
            orientation: {
              heading :Cesium.Math.toRadians(35), // 方向
              pitch :Cesium.Math.toRadians(-90.0),// 倾斜角度
              roll :0
            },
          });
        });

        window.viewer = viewer;

        var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        window.handler = handler;

        handler.setInputAction(function(movement) {
          let ray = viewer.camera.getPickRay(movement.position);
          let cartesian = viewer.scene.globe.pick(ray, viewer.scene);
          let cartographic = Cesium.Cartographic.fromCartesian(cartesian);
          let lng = Cesium.Math.toDegrees(cartographic.longitude); // 经度
          let lat = Cesium.Math.toDegrees(cartographic.latitude); // 纬度
          let alt = cartographic.height; // 高度
          let coordinate = {
              longitude: Number(lng.toFixed(14)),
              latitude: Number(lat.toFixed(14)),
              altitude: Number(alt.toFixed(8))
          };
          console.log(coordinate)
          var pick = viewer.scene.pick(movement.position);
          if(pick!=undefined&&pick.id!=undefined){
            // this.loadPoints();
            let data = {
              planeX: pick.id.infos.PLANEX,
              planeY: pick.id.infos.PLANEY,
              rects: _this.rects
            }
            let url = "http://localhost:9500/transRects"
            axios
            .post(url,data)
            .then((res) => {
              if(res.data.length>0){
                for(let i=0;i<res.data.length;i++){
                  let point = res.data[i];
                  let positions = Cesium.Cartesian3.fromDegreesArray(
                    [point.ltX,point.ltY,point.rtX,point.rtY,point.rbX,point.rbY,point.lbX,point.lbY,point.ltX,point.ltY]
                  );
                  viewer.entities.add({
                    name : '',
                    polygon : {
                      hierarchy : positions,
                      height : 0,
                      material : Cesium.Color.RED.withAlpha(0),
                    },
                    polyline: {
                      positions: positions,
                      width: 5,
                      material: Cesium.Color.RED,
                      clampToGround: true,
                    },
                  });
                }
              }
            })
            .catch((response) => {
              this.$message.error("数据错误");
            });
          }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      },
    },
  }

</script>
<style lang="scss" scoped>
  html,
  body,

  #container{
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    overflow: hidden;
    position: absolute;
  }
  #cesiumContainer {
    width: inherit;
    height: inherit;
  }

  .box {
    height: 100%;
  }

  .special_focus_toolTip {
    margin: 5px;
    z-index: 7;
    position: absolute;
    display: block;
    width: 460px;
    height: auto;
    border-style: solid;
    transition: left 0.4s cubic-bezier(0.23, 1, 0.32, 1),
      top 0.4s cubic-bezier(0.23, 1, 0.32, 1);
    background: rgba(66, 85, 99, 0.5);
    border-width: 0px;
    border: 1px solid aqua;
    border-radius: 4px;
    color: #ffffff;
    font-style: normal;
    font-variant: normal;
    font-weight: normal;
    font-stretch: normal;
    font-size: 14px;
    font-family: "Microsoft YaHei";
    line-height: 21px;
    padding: 10px 10px;
  }
/* 下划线切换高亮 */
::v-deep .el-tabs__active-bar {
  background-color: yellow;
}

::v-deep .el-tabs__nav-wrap::after {
  background-color: aqua
}

/* 鼠标选中时样式 */
::v-deep .el-tabs__item.is-active {
  color: yellow;
  opacity: 1;
}
/* 鼠标悬浮时样式 */
::v-deep .el-tabs__item:hover {
  color: yellow;
  cursor: pointer;
  opacity: 1;
}
::v-deep .el-tabs__item {
  color: aqua;
  opacity: 1;
}
::v-deep .el-input__inner {
  background-color: transparent !important;
  color:aqua;
  border: 1px solid aqua;
}

::v-deep .el-input__inner::-webkit-input-placeholder{
  color: aqua; // 初始化的文字颜色
}

/*最外层透明*/
::v-deep .el-table{
  background-color: transparent !important;
  color: aqua;
  border: none !important;
  border-bottom: 1px solid aqua !important;
}

::v-deep .el-table th {
  background-color: transparent!important;
  border: 1px solid aqua !important;
  color: aqua;
}

::v-deep .el-table tr {
  background-color: transparent !important;
  border: 1px solid aqua !important;
}

::v-deep .el-table td {
  background-color: transparent!important;
  border: 1px solid aqua !important;
}

::v-deep .el-pagination.is-background .btn-prev {
  background: transparent !important; 
  border: 1px solid aqua;
  color: aqua;
}
::v-deep .el-pagination.is-background .btn-next{
  background: transparent !important; 
  border: 1px solid aqua;
  color: aqua;
}
#bottom-right {
  background: rgba(66, 85, 99, 0.8);
  padding: 4px;
  border-radius: 4px;
  position: absolute;
  display: block;
  height: auto;
  top: 0px;
  right: 0px;
}
::v-deep .el-tree{
  background: transparent !important; 
  color: aqua;
}
::v-deep .el-tree-node__content:hover {
  background: rgba(104,147,215,0.4);// hover 节点背景色，否则是白色
}
::v-deep .el-tree-node:focus>.el-tree-node__content {
  background-color: rgba(0,0,0,0); // focus 节点背景透明，否则是白色
}
</style>
